//
//  HMStatusPictureView.swift
//  Weibo
//
//  Created by 黄亦寒 on 2016/9/25.
//  Copyright © 2016年 HM. All rights reserved.
//

import UIKit
import SDWebImage
//图片之间的间距
let itemMargin:CGFloat = 5
//每张图片的宽度和高度相等
let itemWidth = (ScreenWidth - 2 * HMHomeCellMargin - 2 * itemMargin) / 3
//自定义首页配图视图
class HMStatusPictureView: UICollectionView {

    //设置配图数据源
    var picUrls:[HMStatusPictureInfo]? {
        didSet {
            
                messageLabel.text = "\(picUrls?.count ?? 0)"
                
                let size = calcSize(count: picUrls?.count ?? 0)
                
                //设置配图的约束
                self.snp_updateConstraints(closure: { (make) in
                    make.size.equalTo(size)
                })
            
            //刷新列表
            self.reloadData()
        }
        
        
    }
    
    //懒加载控件
    private lazy var messageLabel:UILabel = {
        let label = UILabel(textColor:UIColor.blue,fontSize:20)
        
        return label
    }()
    
    override init(frame: CGRect, collectionViewLayout layout: UICollectionViewLayout) {
        //创建布局对象
        let flowLayout = UICollectionViewFlowLayout()
        //设置大小
        flowLayout.itemSize = CGSize(width:itemWidth,height :itemWidth)
        //垂直间距
        flowLayout.minimumLineSpacing = itemMargin
        //水平间距
        flowLayout.minimumInteritemSpacing = itemMargin
        super.init(frame: frame, collectionViewLayout: flowLayout)
        setUpUI()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    private func setUpUI() {
        
        //设置数据源
        self.dataSource = self
        //设置代理
        self.delegate = self
        //注册cell
        register(HMStatusPictureViewCell.self, forCellWithReuseIdentifier: "cell")
        addSubview(messageLabel)
        
        messageLabel.snp_makeConstraints { (make) in
            make.center.equalTo(self)
        }
        
    }
    
    //根据图片数量计算配图大小
    private func calcSize(count:Int)->CGSize {
        //判断图片个数是否为1，如果为1就从缓存中取出
        if count == 1 {
            let imageUrl = picUrls?.first?.thumbnail_pic
            //根据url从缓存中取图片
            let image = SDWebImageManager.shared().imageCache.imageFromDiskCache(forKey: imageUrl)
            
            if image != nil {
                //获取图片大小
                var size = image!.size
                //如果图片宽度小于指定大小，需要等比例计算图片高度
                if  size.width < 80 {
                    //指定宽度
                    let scaleWidth:CGFloat = 80
                    let height = scaleWidth / size.height * size.width
                    let scaleHeight = height > 150 ? 150 : height
                    
                    size.width = scaleWidth
                    size.height = scaleHeight
                }
                
                size = CGSize(width:itemWidth,height:itemWidth)
                //调整大小
                let flowLayout = self.collectionViewLayout as! UICollectionViewFlowLayout
                flowLayout.itemSize = size
                return size
            }
        }
        
        //如果不是单张图片，需要修改成原始大小
        let flowLayout = self.collectionViewLayout as! UICollectionViewFlowLayout
        flowLayout.itemSize = CGSize(width:itemWidth,height:itemWidth)
        
        //列数
        let cols = count > 3 ? 3 : count
        //行数
        let row = (count - 1) / 3 + 1
        //计算配图的宽度和高度
        let currentWidth = itemWidth * CGFloat(cols) + CGFloat(cols - 1) * itemMargin
        let currentHeight = itemWidth * CGFloat(row) + CGFloat(row - 1) * itemMargin
        
        return CGSize(width:currentWidth,height:currentHeight)
        
    }
}

//数据源方法
extension HMStatusPictureView:UICollectionViewDataSource,UICollectionViewDelegate,SDPhotoBrowserDelegate {
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return picUrls?.count ?? 0
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath) as! HMStatusPictureViewCell
        
        cell.statusPictureInfo = picUrls?[indexPath.row]
        return cell
        
    }
    
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        let photoBrowser = SDPhotoBrowser()
        photoBrowser.delegate = self
        photoBrowser.currentImageIndex = indexPath.item
        photoBrowser.imageCount = picUrls!.count
        photoBrowser.sourceImagesContainerView = self
        photoBrowser.show()
        
    }
    
    func photoBrowser(_ browser: SDPhotoBrowser!, highQualityImageURLFor index: Int) -> URL! {
        let urlStr = picUrls![index].thumbnail_pic!.replacingOccurrences(of: "thumbnall", with: "bmiddle")
        return URL(string: urlStr)
        
    }
    
    func photoBrowser(_ browser: SDPhotoBrowser!, placeholderImageFor index: Int) -> UIImage! {
        let cell = self.cellForItem(at:IndexPath(item: index, section: 0)) as! HMStatusPictureViewCell
        return cell.imageView.image
        
    }
}

//自定义配图cell
class HMStatusPictureViewCell:UICollectionViewCell {
    //设置模型数据
    var statusPictureInfo:HMStatusPictureInfo? {
        didSet {
            if let url = statusPictureInfo?.thumbnail_pic {
                imageView.sd_setImage(with: URL(string:url), placeholderImage: UIImage(named:"timeline_image_placeholder"))
                
                //判断后缀是否是.gif
                if url.hasSuffix(".gif") {
                    gifImageView.isHidden = false
                }else{
                    gifImageView.isHidden = true
                }
            }
            
            
        }
    }
    
    //懒加载控件
    lazy var imageView:UIImageView = {
        let view = UIImageView(image:UIImage(named:"timeline_image_placeholder"))
        //等比例原样显示
        view.contentMode = .scaleAspectFill
        //去除超出部分
        view.clipsToBounds = true

        return view
    }()
    
    //gif标识
    private lazy var gifImageView:UIImageView = UIImageView(image:UIImage(named:"timeline_image_gif"))
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        setUpUI()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    func setUpUI() {
        addSubview(imageView)
        addSubview(gifImageView)
        //设置约束
        imageView.snp_makeConstraints { (make) in
            make.size.equalTo(self)
        }
        
        gifImageView.snp_makeConstraints { (make) in
            make.bottom.equalTo(imageView)
            make.right.equalTo(imageView)
        }
    }
}
